﻿// copyright (c) 2025 author:fio66<fio66@foxmail.com>. All rights reserved.
// date: 2025-10-27 17:29:37

#include "src/common/audio_helper.h"

#include <fstream>

#include <fileref.h>
#include <tag.h>
#include <tpropertymap.h>
#include <tstringlist.h>
#include <tvariant.h>

#include "src/common/utils.h"

namespace fio66::audio_helper {
std::optional<AudioFileInfo> GetAudioFileInfo(std::string_view file_path) {
  TagLib::FileRef f(file_path.data());
  if (f.isNull() || !f.tag()) {
    return std::nullopt;
  }
  AudioFileInfo audio_file_info;
  auto tag = f.tag();
  
  audio_file_info.title = utils::WStringToString(tag->title().toWString());
  audio_file_info.artist = utils::WStringToString(tag->artist().toWString());
  audio_file_info.album = utils::WStringToString(tag->album().toWString());
  audio_file_info.duration = f.audioProperties()->lengthInSeconds();
  audio_file_info.file_path = file_path;

  TagLib::StringList names = f.complexPropertyKeys();
  for (const auto &name : names) {
    const auto &properties = f.complexProperties(name);
    for (const auto &property : properties) {
      for (const auto &[key, value] : property) {
        if (value.type() == TagLib::Variant::ByteVector) {
          const auto& vec_data = value.value<TagLib::ByteVector>();
          audio_file_info.album_pic = std::vector<char>(vec_data.begin(), vec_data.end());
        }
      }
    }
  }
  return audio_file_info;
}
}  // namespace fio66::audio_helper
